let balance = 100;
function withdraw(amount) {
  if (balance >= amount) {
    balance = balance - amount;
    return balance;
  }
  return 'not enough money';
}

withdraw(25); // 75
withdraw(25); // 50
withdraw(60); // 'not enough money'
withdraw(15); // 35

function makeWithdraw() {
  let balance = 100;
  return function withdraw(amount) {
    if (balance >= amount) {
      balance -= amount;
      return balance;
    }
    return 'not enough money';
  };
}

// function makeAccount(balance) {
//   return function dispatch(method, amount) {
//     if (method === 'withdraw') return withdraw(amount);
//     if (method === 'deposit') return deposit(amount);
//     return 'no such method';
//   };

//   function withdraw(amount) {
//     if (balance >= amount) {
//       balance -= amount;
//       return balance;
//     }
//     return 'not enough money';
//   }

//   function deposit(amount) {
//     balance += amount;
//     return balance;
//   }
// }
// const acc = makeAccount(100);
// console.log(acc('abc', 100));

// 练习
let A = makeAccumulator(5);
// A(10); // 15
// A(10); // 25
function makeAccumulator(n) {
  return function (A) {
    n = A + n;
    return n;
  };
}
console.log(A(10));
console.log(A(10));

// 练习 修改 makeAccount 添加密码
// 练习 修改 makeAccount 连续7次密码错误 呼叫警察 call the cops
function makeAccount(balance, password) {
  let i = 0;
  return function dispatch(method, amount, input) {
    if (method === 'withdraw') {
      if (i === 6) return 'call the cops';
      if (input === password) {
        i = 0;
        return withdraw(amount);
      }
      i += 1;
      return 'wrong';
    }
    if (method === 'deposit') return deposit(amount);
    return 'no such method';
  };

  function withdraw(amount) {
    if (balance >= amount) {
      balance -= amount;
      return balance;
    }
    return 'not enough money';
  }
  function deposit(amount) {
    balance += amount;
    return balance;
  }
}

const acc = makeAccount(100, '123456');
console.log(acc('withdraw', 100, '12345'));
console.log(acc('withdraw', 20, '123456'));
console.log(acc('deposit', 200));
